<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Gallery extends Controller_Abstract_Layout {

    public function action_index() {
        $gallery = ORM::factory('gallery')->find_all();
        $this->template->set('content', View::factory('gallery/index', array('gallery' => $gallery)));
    }

    public function action_create() {
        if ($this->request->method() !== Request::POST) {
            $this->request->redirect('gallery/index');
        }

        var_dump($_FILES);

        try {
            $model = ORM::factory('gallery');
            $model->values($this->request->post(), array('textData'));
            $this->_uploadImage($model);
            $model->save();
        }catch (ORM_Validation_Exception $e) {
            $errors = $e->errors('models');
            Session::instance()->set('errors', $errors);
        }

        $this->request->redirect('gallery/index');
    }

    protected function _uploadImage($model) {
         $files = Validation::factory($_FILES)
            ->rule('image', 'Upload::not_empty')
            ->rule('image', 'Upload::size', array(':value', '1M'))
            ->rule('image', 'Upload::type', array(':value', $this->config['gallery']['allowedTypes']));

        if( ! $files->check()) {
            throw new ORM_Validation_Exception('gallery', $files);
        }

        Upload::$remove_spaces = TRUE;
        Upload::$default_directory = $this->config['gallery']['uploadDir'];

        $imageData = pathinfo($_FILES['image']['name']);

        $imageName = $imageData['filename'];
        $imageExt = $imageData['extension'];

        $model->imageFilename = md5($imageName . microtime()) . '.' . $imageExt;

        Upload::save($_FILES['image'], $model->imageFilename);

        $thumbnail = Image::factory(Upload::$default_directory . '/' . $model->imageFilename);
        $thumbnail->crop($this->config['gallery']['thumbSize']['width'], $this->config['gallery']['thumbSize']['height']);
        $thumbName = $this->config['gallery']['thumbPrefix'] . $model->imageFilename;

        $thumbnail->save(Upload::$default_directory . '/' . $thumbName);

        $model->thumbFilename = $thumbName;
    }

}
